package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"live-broadcast_07_23/api/request"
	"live-broadcast_07_23/global"
	"live-broadcast_07_23/internal/model"
	"live-broadcast_07_23/pkg"
	"net/http"
	"path/filepath"
	"strings"
	"time"
)

func UploadAuth(c *gin.Context) {

	file, err := c.FormFile("image")

	if err != nil {
		return
	}

	if file.Size > 5*1024*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "限定上传大小不得超过5MB",
			"data": nil,
		})
		return
	}

	etc := strings.ToLower(filepath.Ext(file.Filename))
	if !strings.Contains(".jpg.png.webp", etc) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "限定上传类型为,jpg/png/webp",
			"data": nil,
		})
		return
	}

	upload := pkg.Upload()

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "图片上传成功",
		"data": upload,
	})

	global.RDB.Set(context.Background(), fmt.Sprintf("%T", time.Now().UnixMilli()), upload, time.Hour)
	global.RDB.Incr(context.Background(), fmt.Sprintf("uploadNum%d", upload.Bucket))

}

func ListUpload(c *gin.Context) {

	var upload model.Upload

	get := global.RDB.Get(context.Background(), "list")
	if get.Val() == "" {
		listUpload, err := upload.ListUpload()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 100000,
				"msg":  "查看失败",
				"data": nil,
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "查看成功",
			"data": listUpload,
		})

		marshal, err := json.Marshal(listUpload)
		if err != nil {
			return
		}

		global.RDB.Set(context.Background(), "list", marshal, time.Minute*30)

	} else {
		json.Unmarshal([]byte(get.String()), &upload)
	}

}

func DeleteUploadAuth(c *gin.Context) {

}

func ShowUploadAuth(c *gin.Context) {
	var req request.ShowUploadAuthForm
	var upload model.Upload

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	upload.Id = req.Id

	upload.GetOneUpload()

	global.RDB.Incr(context.Background(), fmt.Sprintf("uploadShowNum:%d", upload.Id))

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "查看成功",
		"data": upload,
	})

}
